var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var emptyUtil = require('../../templates/empty/empty.js')
var app = getApp()
var that, timeInterval

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderResult: null, //订单结果数据

    payWey:null, //支付方式 ebank网银 wxpay微信
    payStatus: null, //1,待支付 2,支付中 3,未付款  4,支付超时  5，付款成功
    payTime: ["00","00","00"], //支付剩余时间

    statusText:"等待付款", //支付状态文字，默认待支付
    statusImg: "/resources/image/order_status_going.png",//支付状态图片，默认待支付

    ed: "/resources/image/icon_select_ed.png",
    no:"/resources/image/icon_select_no.png",
    emptyParam: {
      emptyStatus: 0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    try {
      //获取在线支付订单结算信息
      httpUtil.PostRequest("online_order_pay_info", {
        orderId: options.orderId
      }, {
          success(res) {
            var payType = res.payTypeList.filter(function (e) { //检索是否含有微信支付方式，有则默认微信支付
              if(e.type=="wxpay"&&e.isShowBtn==1){
                return true;
              }
            });
            if(payType.length==0){
              that.setData({
                orderResult: res,
                payWey: res.payTypeList[0].type
              })
            } else {
              that.setData({
                orderResult: res,
                payWey: payType[0].type||null
              })
            }
            that.toPayStatus(1);
            that.surplusPayTime(res.waitPayTime); //开启支付倒计时
          },
          fail(code, res) {
            emptyUtil.showFailView(res ||"加载失败，请稍后重试");
          },
          complete() {

          }
        })
    } catch (e) {
      console.log(e)
    }
  },

  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () {
    clearInterval(timeInterval); //页面卸载，清除支付倒计时
  },
  
  // 更改支付状态
  toPayStatus(res){
    that.setData({
      payStatus: res
    })
    if (res==1){
      that.setData({
        statusText: "待付款",
        statusImg: "/resources/image/order_status_going.png"
      })
    } else if (res == 2) {
      that.setData({
        statusText: "支付中",
        statusImg: "/resources/image/order_status_going.png"
      })
    } else if (res == 3) {
      that.setData({
        statusText: "未付款",
        statusImg: "/resources/image/order_status_going.png"
      })
    } else if (res == 4) {
      clearInterval(timeInterval);
      that.setData({
        statusText: "支付超时",
        statusImg: "/resources/image/order_status_fail.png",
        payTime: ["00", "00", "00"]
      })
    } else if (res == 5) {
      clearInterval(timeInterval);
      that.setData({
        statusText: "付款成功",
        statusImg: "/resources/image/order_status_success.png"
      })
    }
  },

  // 支付剩余时间
  surplusPayTime(res){ 
    var maxtime = Math.floor(parseInt(res)/1000);
    var day,hour,minutes, seconds,d,h, m, s, time, payTime;
    timeInterval = setInterval(()=>{
      if (maxtime >= 0) { 
        if (maxtime>86400){ //倒计时大于一天
          day = Math.floor(maxtime / 86400);
          hour = Math.floor((maxtime % 86400) / 3600);
          minutes = Math.floor(((maxtime % 86400) % 3600) / 60);
          if (hour < 10) { h = "0"; } else { h = ""; }
          if (minutes < 10) { m = "0"; } else { m = ""; }
          time = String(day) + " 天" + "," + h + String(hour) + "," + m + String(minutes) ;
        } else { //倒计时小于一天
          hour = Math.floor(maxtime / 3600);
          minutes = Math.floor((maxtime % 3600) / 60);
          seconds = Math.floor((maxtime % 3600) % 60);
          if (hour < 10) { h = "0"; } else { h = ""; }
          if (minutes < 10) { m = "0"; } else { m = ""; }
          if (seconds < 10) { s = "0"; } else { s = ""; }
          time = h + String(hour) + "," + m + String(minutes) + "," + s + String(seconds);
        }
        
        payTime=time.split(",");
        that.setData({
          payTime: payTime
        });
        --maxtime;

      } else { //支付时间结束
        uiUtil.showToast("支付超时");
        that.toPayStatus(4);
      }
    }, 1000);  
  },


  // 更改支付方式
  toPayWey(res) {
    let payWey = res.currentTarget.dataset.wey;
    if (that.data.payStatus==1||that.data.payStatus==3){
      this.setData({
        payWey: payWey
      })
    }
  },
  
  // 确认支付订单，调起相应支付
  payment() {
    if (that.data.payStatus==1||that.data.payStatus==3){ //支付状态限制，预防重复请求支付
      if(that.data.payWey == "ebank"){
          that.ebankPayment();
      } else if (that.data.payWey=="wxpay"){
        uiUtil.showLoading("请稍候..");
        that.toPayStatus(2);
        that.wxPayment();
      }
    }
  },

  // 网银在线支付
  ebankPayment() {
    wx.scanCode({ //打开扫一扫
      onlyFromCamera: true,
      scanType:['qrCode'],
      success (res) {
        let qrcode=res.result.split("code=")[1];
        if(qrcode==undefined){
          uiUtil.showToast("扫码失败");
        } else {
          that.showModal(qrcode);
        }
      },
      fail(res) {
        uiUtil.showToast("扫码失败");
      }
    })    
  },

  //网银在线支付,用户选择是否登录
  showModal(qrcode){
    wx.showModal({
      title: '是否登录？',
      // content: '这是一个模态弹窗',
      success (res) {
        if (res.confirm) { //用户点击确定
          that.ebankLogin(qrcode);
          uiUtil.showLoading("请稍候..");
        } else if (res.cancel) { //用户点击取消

        }
      }
    }) 
  },
  
  // 网银登录
  ebankLogin(qrcode){
    httpUtil.PostRequest("highpay_user_login", {
      loginId: app.globalData.loginCode,
      qrcode: qrcode
    }, {
      success(res) {
        uiUtil.showToast("登录成功");
        setTimeout(function(){
          wx.navigateBack({
            delta: 1
          })
        },1500)
      },
      fail(code, res) {
        console.log(code,res)
        uiUtil.showToast("登录失败");
      },
      complete() { }
    })
  },


  // 微信在线支付
  wxPayment(){
    httpUtil.PostRequest("order_pay_by_wx", {
      orderId: that.data.orderResult.orderId
    }, {
      success(res) {
        if(that.data.payStatus!==4){
          that.wx_payment(res);
        }
      },
      fail(code, res) {
        if(that.data.payStatus!==4){
          that.toPayStatus(1);
        }
        uiUtil.showToast(res || "加载失败,请稍候重试")
      },
      complete() { }
    })

  },

  // 调用客户端微信支付
  wx_payment(res) {
    uiUtil.hideLoading();
    var pay = JSON.parse(res.weixinPayInfo);
    wx.requestPayment({
      timeStamp: pay.timeStamp,
      nonceStr: pay.nonceStr,
      package: pay.package,
      signType: pay.signType,
      paySign: pay.paySign,
      success(res) {
        that.informOrderPay("success");
        that.toPayStatus(5);
        uiUtil.showLoading("请稍候..");
      },
      fail(res) {
        if(that.data.payStatus!==4){
          that.toPayStatus(3);
        }
      }
    })
  },

  // 向服务器通知支付结果
  informOrderPay(payStatus) {
    httpUtil.PostRequest("inform_order_pay_result", {
      orderId: that.data.orderResult.orderId,
      payType: "wxpay",
      payStatus: payStatus
    }, {
        success(res) {},
        fail(code, res) {},
        complete() {
          uiUtil.hideLoading();
          wx.redirectTo({
            url: '/pages/order/online-polling/online-polling?orderResult=' + encodeURIComponent(JSON.stringify(that.data.orderResult))
          })
        }
      })
  }

})
